/* eslint-disable no-unused-vars */
import {
  Cartesian3, Cartographic, defined, Ray, SceneMode,
} from 'cesium/Cesium';

const Utils = {};

const unprojectedScratch = new Cartographic();
const rayScratch = new Ray();

/**
 * 获取笛卡尔坐标系
 * @param {Viewer|Widget} terria 三维场景
 * @param {boolean} inWorldCoordinates 世界坐标系单位是米 * 
 * @param {Cartesian3} [result] 放回对象
 * @return {Cartesian3} The modified result parameter, a new instance if none was provided or undefined if there is no focus point.
 */
Utils.getCameraFocus = function (terria, inWorldCoordinates, result) {
  const { scene } = terria;
  const { camera } = scene;

  if (scene.mode === SceneMode.MORPHING) {
    return undefined;
  }

  if (!defined(result)) {
    result = new Cartesian3();
  }

  // TODO bug when tracking: if entity moves the current position should be used and not only the one when starting orbiting/rotating
  // TODO bug when tracking: reset should reset to default view of tracked entity

  if (defined(terria.trackedEntity)) {
    result = terria.trackedEntity.position.getValue(terria.clock.currentTime, result);
  } else {
    rayScratch.origin = camera.positionWC;
    rayScratch.direction = camera.directionWC;
    result = scene.globe.pick(rayScratch, scene, result);
  }

  if (!defined(result)) {
    return undefined;
  }

  if (scene.mode === SceneMode.SCENE2D || scene.mode === SceneMode.COLUMBUS_VIEW) {
    result = camera.worldToCameraCoordinatesPoint(result, result);

    if (inWorldCoordinates) {
      result = scene.globe.ellipsoid.cartographicToCartesian(scene.mapProjection.unproject(result, unprojectedScratch), result);
    }
  } else if (!inWorldCoordinates) {
    result = camera.worldToCameraCoordinatesPoint(result, result);
  }

  return result;
};
export default Utils;
